package com.huike;

import com.huike.common.exception.CustomException;
import io.jsonwebtoken.*;

import java.util.Date;

public class JavaJwt {
    static String signature = "lzzzb";

    public static void main(String[] args) {

        //使用jjwt自带的构造器构造一个jwt
        JwtBuilder builder = Jwts.builder();

        String token = builder.
                setHeaderParam("type","JWT").
                setHeaderParam("alg","HS256")
                .claim("username","zhangsan")
                .claim("name","张三")
                .claim("age","23")
                .claim("sex","男")
                //在payload中设置一个超时时间 秒   分   时
                .setExpiration(new Date(System.currentTimeMillis()+Long.valueOf(1000*10)))
                .setSubject("10086")
                .setId("121212")
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        System.out.println(token);

        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            throw new CustomException("睡眠失败1");
        }

        JwtParser parser = Jwts.parser();
        Jws<Claims> claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        //获取用户名
        System.out.println(body.get("username"));
        //获取name
        System.out.println(body.get("name"));
        //获取年龄
        System.out.println(body.get("age"));
        //获取性别
        System.out.println(body.get("sex"));
        //获取id
        System.out.println(body.getId());
        //获取有效期-截止时间
        System.out.println(body.getSubject());
        System.out.println(body.getExpiration());
    }

}
